package com.fqh.service.impl;

import com.fqh.dto.PayInfo;
import com.fqh.entity.*;
import com.fqh.mapper.OrderMapper;
import com.fqh.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.UnsupportedEncodingException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@Transactional
@Service
public class OrderServiceImpl implements OrderService {

    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private OrderMapper orderMapper;

    public void orderFood(String name, String id, String number) {
        String foodNumStr = (String) redisTemplate.boundHashOps(name).get(id);
        if ("".equals(foodNumStr) || foodNumStr == null) {
            redisTemplate.boundHashOps(name).put(id, number);
        } else {
            int foodNum = Integer.parseInt(foodNumStr);
            int numStr = Integer.parseInt(number);
            foodNum += numStr;
            redisTemplate.boundHashOps(name).put(id, foodNum + "");

        }
    }

    public void addMenu(String loginName, String foodId) {
        String foodNumStr = (String) redisTemplate.boundHashOps(loginName).get(foodId);
        if ("".equals(foodNumStr) || foodNumStr == null) {
            redisTemplate.boundHashOps(loginName).put(foodId, "1");
        } else {
            int foodNum = Integer.parseInt(foodNumStr);
            foodNum++;
            redisTemplate.boundHashOps(loginName).put(foodId, foodNum + "");
        }
    }

    public Integer alreadyOrder(String loginName) {
        List list = redisTemplate.boundHashOps(loginName).values();
        return list.size();
    }

    public List findAllList(String loginName) {
        Map<String, String> map = redisTemplate.boundHashOps(loginName).entries();
        Set<Map.Entry<String, String>> entries = map.entrySet();
        List list = new ArrayList();
        for (Map.Entry<String, String> entry : entries) {
            GroupResult result = new GroupResult();
            String ss = entry.getKey();
            Fooddetail fooddetail = orderMapper.findDetialByFoodId(Integer.parseInt(ss));
            result.setFooddetail(fooddetail);
            result.setNumber(entry.getValue());
            list.add(result);
        }
        return list;
    }

    public void addNumber(String foodId, String loginName) {
        String foodNumStr = (String) redisTemplate.boundHashOps(loginName).get(foodId);
        Integer foodNum = Integer.parseInt(foodNumStr);
        foodNum++;
        redisTemplate.boundHashOps(loginName).put(foodId, foodNum + "");
    }

    public String reduceNumber(String foodId, String loginName) {
        String foodNumStr = (String) redisTemplate.boundHashOps(loginName).get(foodId);
        Integer foodNum = Integer.parseInt(foodNumStr);
        if (foodNum == 1) {
            return "数量不能小于一";
        } else {
            foodNum--;
            redisTemplate.boundHashOps(loginName).put(foodId, foodNum + "");
            return "success";
        }
    }

    public String delFoodById(String foodId, String loginName) {
        Long delete = redisTemplate.boundHashOps(loginName).delete(foodId);
        if (delete > 0) {
            return "success";
        }
        return "fail";
    }

    public void putInfo(HttpServletRequest request) {

        PayInfo payInfo = getPayInfo(request);
        Login user = payInfo.getUser();
        String time = payInfo.getTime();

        Map<String, String> map = redisTemplate.boundHashOps(user.getLoginName()).entries();

        Set<Map.Entry<String, String>> entries = map.entrySet();
        for (Map.Entry<String, String> entry : entries) {
            Orderinfo orderinfo = new Orderinfo();
            orderinfo.setOrder_number(time);
            orderinfo.setFood_id(Integer.parseInt(entry.getKey()));
            orderinfo.setFood_number(Integer.parseInt(entry.getValue()));
            orderMapper.putInfo(orderinfo);
        }
    }

    public void deleteRedis(HttpServletRequest request) {
        Login user = (Login) getPayInfo(request).getUser();

        redisTemplate.delete(user.getLoginName());
    }

    public void addOrderManage(HttpServletRequest request) {

        PayInfo payInfo = getPayInfo(request);
        Login user = payInfo.getUser();
        String totalPrice = payInfo.getTotalPrice();
        String tableNum = payInfo.getTableNum();
        String orderNum = payInfo.getOrderNum();

        Order1 order = new Order1();
        order.setOrderNumber(orderNum);
        order.setFoodPrice(Double.parseDouble(totalPrice));
        order.setLoginId(user.getLoginId());
        order.setOrderState("已支付");
        order.setTableId(tableNum);
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String string = sdf.format(new Date().getTime());
            Date date = sdf.parse(string);
            order.setDate(date);
            orderMapper.addOrderManage(order);
        } catch (ParseException e) {
            e.printStackTrace();
        }
    }

    public List<Order1> findAllOrder(Integer loginId) {
        return orderMapper.findAllOrder(loginId);
    }


    public PayInfo getPayInfo(HttpServletRequest request) {
        try {
            Map<String, String> params = getPayRequestParam(request);

            return (PayInfo) request.getServletContext().getAttribute(params.get("out_trade_no"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            throw new RuntimeException("请求回调失败");
        }
    }

    public Map<String, String> getPayRequestParam(HttpServletRequest request) throws UnsupportedEncodingException {
        Map<String, String> params = new HashMap<String, String>();
        Map<String, String[]> requestParams = request.getParameterMap();


        for (String key : requestParams.keySet()) {
            String[] values = requestParams.get(key);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            //乱码解决，这段代码在出现乱码时使用
            valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
            params.put(key, valueStr);
        }

        return params;
    }

    public void updateSessionByPayInfo(HttpServletRequest request) {
        PayInfo payInfo = getPayInfo(request);

        HttpSession session = request.getSession();

        session.setAttribute("user", payInfo.getUser());

//        Login user  = (Login)session.getAttribute("user");
//        String time = (String) session.getAttribute("time");
//        String totalPrice = (String) session.getAttribute("totalPrice");
//        String tableNum = (String) session.getAttribute("tableNum");
//        String orderNum = (String) session.getAttribute("time");
    }
}
